﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Data;
using MySQL.Db;
using NLog;

namespace Gollie.Mail
{
	public class BulkMail : Collection<string>
	{
		private static readonly Logger logger = LogManager.GetCurrentClassLogger();

		private string Body {get; set;}
		private string Subject { get; set; }

		public BulkMail(string body, string subject)
		{
			this.Body = new string((body.Where(c => c.CompareTo(' ') >= 0)).ToArray());
			this.Subject = subject;
		}

		public void DoQueue()
		{
			try
			{
				logger.Info("Sending bulkmail to {0} members", this.Count);

				QueryArguments args = new QueryArguments();

				args.Add("p_subject", Subject);
				args.Add("p_body", Body);
				args.Add("p_id", (uint)0).Direction = ParameterDirection.Output;

				Query query = new Query("sp_insertmailtext", args);

				query.Execute();

				uint textId = Convert.ToUInt32(args[2].Value);

				QueryCollection queries = new QueryCollection(GollieDb.GollieMail);

				foreach (string email in this)
				{
					QueryArguments bulkArgs = new QueryArguments();
					bulkArgs.Add("p_recipient", email);
					bulkArgs.Add("p_textid", textId);

					Query bulkQuery = new Query("sp_insertsinglebulkmail", bulkArgs);
					queries.Add(bulkQuery);
				}
				logger.Debug("Start queue mailcollection...");
				queries.Execute();
				logger.Debug("End queue mailcollection...");

				logger.Info("{0} mails queued.", this.Count);
			}
			catch (Exception e)
			{
				logger.FatalException("", e);

				throw;
			}
		}
	}
}
